package com.wgchao.amc.autho;

import com.wgchao.amc.common.MenuAutho;
import com.wgchao.amc.repository.base.SysBaseUserRepository;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @作者：wgchao
 * @时间：17:23 2019/8/20 0020
 * @用途：菜单权限验证、检校
 **/
@Aspect
@Component
@Order(-10)
public class AuthenticationAspect {
    private static Logger logger = LoggerFactory.getLogger(AuthenticationAspect.class);


    @Autowired
    private JwtCheck jwtCheck;

    ThreadLocal<Long> beginTime = new ThreadLocal<Long>();

    @Pointcut("@annotation(menuAutho)")
    public void AuthenticationService(MenuAutho menuAutho) {
    }

    @Around("AuthenticationService(menuAutho)")
    public Object doAround(ProceedingJoinPoint joinPoint, MenuAutho menuAutho) throws Throwable{
        beginTime.set(System.currentTimeMillis());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        boolean isPass = true;
        //权限验证
        logger.info("-------------JWT合法性验证");
        String token = request.getHeader("authorization");
        if(StringUtils.isEmpty(token)){
            logger.info("[authentication] authentication reject, cost time: {}", System.currentTimeMillis() - beginTime.get());
            throw new Exception("凭证未上传");
        }
        UserInfo userInfo = jwtCheck.check(token);
        if(userInfo == null){
            logger.info("[authentication] authentication reject, cost time: {}", System.currentTimeMillis() - beginTime.get());
            throw new Exception("凭证合法性验证未通过");
        }

        logger.info("-------------用户菜单权限验证");
        if(menuAutho.require()){
            if(userInfo.getUserType()!=null && userInfo.getUserType() == 1){
                logger.info("[authentication] authentication reject, cost time: {}", System.currentTimeMillis() - beginTime.get());
                throw new Exception("账户类型不符");
            }
        }

        logger.info("[authentication] authentication pass, cost time: {}", System.currentTimeMillis() - beginTime.get());
        HttpSession session = request.getSession();
        session.setAttribute("user", userInfo);
        return joinPoint.proceed();


    }
}
